//
//  Activite.m
//  Grappin
//
//  Created by apple-120 on 4/27/13.
//
//

#import "Activite.h"

/************ add sms ***********/
#define kRecentActivityCellIdentifier @"ActivityCell"
#import "ActivityCell.h"
#import "DTOMessage.h"
#import "Theme.h"
#import "Globals.h"
#import "ActivityViewPage.h"
#import "ViewIdentity.h"
#import "Theme.h"
#import "EntityMessage.h"
#import "FacadeGroup.h"
#import "FacadeContact.h"
#import "FacadeMessage.h"
#import "EntityMessage.h"

/************ end sms ***********/

/************ add sos ***********/
#define kRecentSOSCellIdentifier @"SOSCell"
#import "DTOSOS.h"
#import "SOSCell.h"
#import "SOSDetailPage.h"
/************ end sos ***********/

@interface Activite ()
/************ add sms ***********/
@property (retain, nonatomic) NSMutableArray * activities;

- (void)onClick_MoreButtonHandler;
/************ end sms ***********/

/************ add sos ***********/
@property (retain, nonatomic) NSMutableArray * sos;

- (void)onClick_MoreButtonHandler;
/************ end sos ***********/

@end

@implementation Activite
@synthesize activities, isDisplayMoreButton, moreButtonBlock, addMoreButtonMessageText, removeMessageBlock;
@synthesize isDisplayMoreButton, addMoreSOSBlock, removeSOSBlock, addMoreButtonMessageText;
@synthesize sos;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ActivityCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kRecentActivityCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"SOSCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kRecentSOSCellIdentifier];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    int tNumRow = self.activities.count + self.sos.count;
    if (self.isDisplayMoreButton)
        tNumRow++;
        
    return tNumRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row < self.sos.count)
    {
        /************ add sos ***********/
        UITableViewCell * tCell;
        NSString * tIdentifier;
        BOOL tIsDisplayMoreButton = FALSE;
        if (indexPath.row == self.sos.count && self.isDisplayMoreButton)
            tIsDisplayMoreButton    =   TRUE;
        
        if (tIsDisplayMoreButton)
            tIdentifier =   @"buttonMore";
        else
            tIdentifier =   kRecentSOSCellIdentifier;
        
        tCell = [tableView dequeueReusableCellWithIdentifier:tIdentifier];
        
        
        if (!tCell && tIsDisplayMoreButton)
        {
            tCell   =   [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tIdentifier] autorelease];
            
            UIButton * tButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [tButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [tButton setBackgroundImage:[[Theme instance] getImageBy:addMoreButtonBackground640x88] forState:UIControlStateNormal];
            tButton.frame   =   CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f);
            [tButton addTarget:self action:@selector(onClick_MoreButtonHandler) forControlEvents:UIControlEventTouchUpInside];
            [tCell.contentView addSubview:tButton];
            
        }
        
        if (!tIsDisplayMoreButton)
        {
            DTOSOS * tSOS   =   [self.sos objectAtIndex:indexPath.row];
            SOSCell * tSOSCell  =   (SOSCell *) tCell;
            [tSOSCell setDataForCellWithFullName:[NSString stringWithFormat:@"%@ %@", tSOS.senderLastName, tSOS.senderFirstName] address:tSOS.address date:tSOS.lastModificationDate status:tSOS.status];
        }
        else
        {
            UIButton * tButton = (UIButton *)[tCell.contentView.subviews objectAtIndex:0];
            [tButton setTitle:self.addMoreButtonMessageText forState:UIControlStateNormal];
        }
        /************ add sos ***********/
    }
    else
    {
        /************ add sms ***********/
        UITableViewCell * tCell;
        NSString * tIdentifier;
        BOOL tIsDisplayMoreButton = FALSE;
        if (indexPath.row == self.activities.count && self.isDisplayMoreButton)
            tIsDisplayMoreButton    =   TRUE;
        
        if (tIsDisplayMoreButton)
            tIdentifier =   @"buttonMore";
        else
            tIdentifier =   kRecentActivityCellIdentifier;
        
        tCell = [tableView dequeueReusableCellWithIdentifier:tIdentifier];
        
        if (!tCell && tIsDisplayMoreButton)
        {
            tCell   =   [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"buttonMore"] autorelease];
            
            UIButton * tButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [tButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [tButton setBackgroundImage:[[Theme instance] getImageBy:addMoreButtonBackground640x88] forState:UIControlStateNormal];
            tButton.frame   =   CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f);
            [tButton addTarget:self action:@selector(onClick_MoreButtonHandler) forControlEvents:UIControlEventTouchUpInside];
            [tCell.contentView addSubview:tButton];
        }
        
        if (!tIsDisplayMoreButton)
        {
            ActivityCell * tActivityCell = (ActivityCell *) tCell;
            int tIndex = indexPath.row;
            DTOMessage * tMessage       =   [self.activities objectAtIndex:tIndex];
            BOOL tSetBoldForMessage     =   FALSE;
            if (!tMessage.isRead)
                tSetBoldForMessage      =   TRUE;
            
            [tActivityCell setBoldForMessageLabel:tSetBoldForMessage];
            [tActivityCell setMessage:tMessage.message];
            [tActivityCell setSender:[NSString stringWithFormat:@"%@ %@", tMessage.contactFirstName, tMessage.contactLastName]];
            [tActivityCell setReceiveDate:[tMessage getFormatedReceiveDateStyleOne]];
        }
        else
        {
            UIButton * tButton = (UIButton *)[tCell.contentView.subviews objectAtIndex:0];
            [tButton setTitle:self.addMoreButtonMessageText forState:UIControlStateNormal];
        }
        
        /************ end sms ***********/
    }   
    
    return tCell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        DTOMessage * tMessage = [self.activities objectAtIndex:indexPath.row];
        if (self.removeMessageBlock)
            self.removeMessageBlock(tMessage, indexPath);
        
        DTOSOS * tSOS = [self.sos objectAtIndex:indexPath.row];
        if (self.removeSOSBlock)
            self.removeSOSBlock(tSOS, indexPath);
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < self.activities.count)
    {
        DTOMessage * tMessage = [self.activities objectAtIndex:indexPath.row];
        NSString * tIdentity = NSStringFromClass([ActivityViewPage class]);
        
        BOOL tCanResponse = FALSE;
        
        if (!tMessage.isRead)
        {
            EntityMessage * tEntityMessage  =   [[FacadeMessage getInstance] findById:[NSString stringWithFormat:@"%i", tMessage.messageId]];
            if (tEntityMessage)
            {
                tEntityMessage.isRead   =   TRUE;
                [[FacadeMessage getInstance] update:tEntityMessage];
            }
        }
        
        if (tMessage.groupId == kGlobalNoneGroupId)
            tCanResponse = [[FacadeContact getInstance] canResponseWithContactId:tMessage.contactId];
        else
            tCanResponse = [[FacadeGroup getInstance] canResponseWithGroupId:tMessage.groupId];
        
        ActivityViewPage * tActivityViewPage =   [[ViewIdentity instance] getInstanceOfClass:tIdentity];
        tActivityViewPage.dtoMessage    =   tMessage;
        tActivityViewPage.displayComposeMessage =   tCanResponse;
        [[Globals instance].navigationController addSubViewToNavigation:tIdentity];
    }
    
    if (indexPath.row < self.sos.count)
    {
        DTOSOS * tSOS = [self.sos objectAtIndex:indexPath.row];
        NSString * tClassName   =   NSStringFromClass([SOSDetailPage class]);
        SOSDetailPage * tDetailPage =   [[ViewIdentity instance] getInstanceOfClass:tClassName];
        tDetailPage.sos =   tSOS;
        [[Globals instance].navigationController addSubViewToNavigation:tClassName];
    }

}

/************ add sms ***********/
// public functions

- (void)addMoreContacts:(NSMutableArray *)pData
{
    if (pData)
    {
        for (int i = 0; i < pData.count; i++)
            [self.activities addObject:[pData objectAtIndex:i]];
        
        [self.tableView reloadData];
    }
}

- (void)setData:(NSMutableArray *)pData
{
    self.activities =   pData;
    [self.tableView reloadData];
}

- (void)removeCellByIndexPath:(NSIndexPath *)pIndexPath
{
    DTOMessage * tMessage = [self.activities objectAtIndex:pIndexPath.row];
    [self.activities removeObject:tMessage];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:pIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

// private methods
- (void)onClick_MoreButtonHandler
{
    if (self.moreButtonBlock)
        self.moreButtonBlock();
}

- (void)dealloc
{
    self.removeMessageBlock =   nil;
    self.moreButtonBlock    =   nil;
    [activities release];
    [super dealloc];
}
/************ end sms ***********/

/************ add sos ***********/
// public functions

- (void)addMoreSOS:(NSMutableArray *)pData
{
    if (pData)
    {
        for (int i = 0; i < pData.count; i++)
            [self.sos addObject:[pData objectAtIndex:i]];
        
        [self.tableView reloadData];
    }
}

- (void)removeCellByIndexPath:(NSIndexPath *)pIndexPath
{
    DTOSOS * tSOS = [self.sos objectAtIndex:pIndexPath.row];
    [self.sos removeObject:tSOS];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:pIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)setData:(NSMutableArray *)pData
{
    self.sos    =   pData;
    [self.tableView reloadData];
}
// private methods
- (void)onClick_MoreButtonHandler
{
    if (self.addMoreSOSBlock)
        self.addMoreSOSBlock();
}

- (void)dealloc
{
    [sos release];
    self.addMoreSOSBlock =   nil;
    self.removeSOSBlock  =   nil;
    [super dealloc];
}





/************ end sos ***********/
@end
